package com.shiku.mongodb.springdata;

import com.mongodb.*;
import com.shiku.utils.StringUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoConverter;

@Configuration
@EnableConfigurationProperties(MongoConfig.class)
public class MongoConfiguration extends AbstractMongoConfiguration implements InitializingBean {

    @Autowired
    private MongoConfig mongoConfig;

   /* @Autowired
    private MongoTemplate mongoTemplate;*/

    public MongoClientOptions getMongoClientOptions(MongoConfig mongoConfig) {
        MongoClientOptions.Builder builder = MongoClientOptions.builder();
        builder.socketKeepAlive(true);
        builder.connectTimeout(mongoConfig.getConnectTimeout());
        builder.socketTimeout(mongoConfig.getSocketTimeout());
        builder.maxWaitTime(mongoConfig.getMaxWaitTime());
        builder.heartbeatFrequency(10000);// 心跳频率

        builder.readPreference(ReadPreference.nearest());
        return builder.build();
    }

    @Bean(name = "mongoClient",destroyMethod = "close")
    @Override
    public MongoClient mongoClient() {
        MongoClient mongoClient=null;
        try {
            MongoClientURI mongoClientURI=new MongoClientURI(mongoConfig.getUri());
            MongoCredential credential = null;
            //是否配置了密码
            if(!StringUtil.isEmpty(mongoConfig.getUsername())&&!StringUtil.isEmpty(mongoConfig.getPassword()))
                credential = MongoCredential.createScramSha1Credential(mongoConfig.getUsername(), mongoConfig.getDbName(),
                        mongoConfig.getPassword().toCharArray());
            mongoClient = new MongoClient(mongoClientURI);
            return mongoClient;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected String getDatabaseName() {
        return mongoConfig.getDbName();
    }




    /*@Bean
    public DefaultConversionService conversionService(){
        DefaultConversionService conversionService=new DefaultConversionService();
        return  conversionService;
    }*/

   /*

   @Bean
    public Jackson2ObjectMapperBuilderCustomizer jsonCustomer() {
        return jsonMapperBuilder -> {
            //添加Mongodb的ObjectId序列化的转换
            jsonMapperBuilder.serializerByType(ObjectId.class, new ToStringSerializer());
        };
    }*/

    @Override
    public void afterPropertiesSet() throws Exception {
        MongoConverter converter = mongoTemplate().getConverter();
        if (converter.getTypeMapper().isTypeKey("_class")) {
            ((MappingMongoConverter) converter).setTypeMapper(new DefaultMongoTypeMapper(null));
        }
    }

}
